package com.example.blog.controller;

import com.example.blog.constants.Constant;
import com.example.blog.model.Blog;
import com.example.blog.model.UserInfo;
import com.example.blog.service.BlogService;
import com.example.blog.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    private BlogService blogService;

    @RequestMapping("/getBlogList")
    public List<Blog> getBlogList(){
        return blogService.selectAll();
    }

    @RequestMapping("/getBlogById")
    public Blog getBlogById(Integer id){
        // 1. 参数校验
        log.info("/blog/getBlogById接收到参数: {}", id);
        if(id == null){
            log.error("id 为空");
            return null;
        }
        // 2. 获取博客信息
        return blogService.selectBlogById(id);
    }

    @RequestMapping("/updateBlogById")
    public Boolean updateBlogById(Blog blog){
        // 1. 参数校验
        log.info("/blog/updateBlogById接收到参数: {}", blog);
        if(blog.getId() == null
                || !StringUtils.hasLength(blog.getTitle())
                || !StringUtils.hasLength(blog.getContent())){
            log.error("输入参数有误");
            return false;
        }
        // 2. 更新博客信息
        Integer result = blogService.updateBlogById(blog);
        if(result <= 0){
            log.error("更新失败");
            return false;
        }

        return true;
    }

    @RequestMapping("/insertBlog")
    public Boolean insertBlog(Blog blog, HttpServletRequest request){
        // 1. 参数校验
        log.info("/blog/updateBlogById接收到参数: {}", blog);
        if(!StringUtils.hasLength(blog.getTitle())
                || !StringUtils.hasLength(blog.getContent())){
            log.error("输入参数有误");
            return false;
        }
        // 2. 从 token 中获取用户信息
        String token = request.getHeader(Constant.USER_LOGIN_TOKEN);
        Integer id = JwtUtil.getCurrentUserIdByToken(token);
        blog.setUserId(id);
        // 3. 新增博客信息
        Integer result = blogService.insertBlog(blog);
        if(result <= 0){
            log.error("新增博客信息失败");
            return false;
        }

        return true;
    }

    @RequestMapping("/deleteBlogById")
    public Boolean deleteBlogById(Integer id){
        // 1. 参数校验
        log.info("/blog/deleteBlogById接收参数：{}", id);
        if(id == null){
            log.error("参数为空");
            return false;
        }
        // 2. 删除博客
        Integer result = blogService.deleteBlogById(id);
        if(result <= 0){
            log.error("删除失败");
            return false;
        }
        return true;
    }
}
